const mysql = require('mysql')
const config = require('./default')

//创建线程池
let pool = mysql.createPool({
    host: config.dataBase.HOST,
    user: config.dataBase.USERNAME,
    password: config.dataBase.PASSWORD,
    database: config.dataBase.DATABASE,
    port: config.dataBase.PORT
})

//连接线程池, 做 sql 查找
let allServices = {
    query: function (sql, values) {
        return new Promise((resolve, reject) => {
            pool.getConnection(function (err, connection) {
                if (err) {
                    reject(err)
                } else {
                    connection.query(sql, values, (err, rows) => {
                        if (err) {
                            reject(err)
                        } else {
                            resolve(rows)
                        }
                        connection.release() //释放连接
                    })
                }
            })
        })

    }
}

//用户登入

let userLogin = function (username, userpwd) {
    let _sql = `select * from users where username="${username}" and userpwd="${userpwd}";`
    return allServices.query(_sql)
}

//查重
let findUser = function (username) {
    let _sql = `select * from users where username="${username}";`
    return allServices.query(_sql)
}

//注册
let addUser = function(value){
 let _sql = `insert into users set username=?,userpwd=?,nickname=?;`
 return allServices.query(_sql,value)
}

//获取文章详情
let findDetailById = function(id, userId){
    let _sql =  `select * from message where msg_id="${id}" and user_id != "${userId}"`
    console.log(allServices.query(_sql));
    return allServices.query(_sql)
}
//获取表行数
let findNum = function() {
  let _sql = `select count(msg_id) from message`
  return allServices.query(_sql)
}

//发布文章
let insertNote = function(value){
    let _sql = `insert into message set user_id=?,title=?,ctx=?;`
    console.log(allServices.query(_sql, value));
    return allServices.query(_sql,value)
   }


// 获取信息页聊天者ID
let findNewsUserid = function (userId) {
    let _sql = `select * from message where user_id=${userId}`
    // console.log(allServices.query(_sql), '23333333333333333333333333333');
    return allServices.query(_sql)
}
module.exports = {
    userLogin,
    findUser,
    addUser,
    findNum,
    findDetailById,
    insertNote,
    findNewsUserid
}
